package assistant

import (
	"context"

	"paper-pro/app/assistant/api/internal/svc"
	"paper-pro/app/assistant/api/internal/types"
	"paper-pro/pkg/ctxdata"
	assistantclient "paper-pro/pkg/rpc/assistant"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type ListMetasLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// list assistant metas
func NewListMetasLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListMetasLogic {
	return &ListMetasLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListMetasLogic) ListMetas() (resp *types.ListMetasResp, err error) {
	userId, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(err, "List Assistant metas: get UserId error: %v", err)
	}

	rpcResp, err := l.svcCtx.AssistantRpc.GetAssistantMetas(l.ctx,
		&assistantclient.GetAssistantMetasReq{UserId: userId})
	if err != nil {
		return nil, errors.Wrapf(err, "List Assistant metas: AssistantRpc GetAssistantMetas error: %v", err)
	}
	metasCount := len(rpcResp.AssistantMetas)
	assistantMetas := make([]types.AssistantMeta, metasCount)
	for i := 0; i < metasCount; i++ {
		assistantMetas[i].Id = rpcResp.AssistantMetas[i].Id
		assistantMetas[i].Name = rpcResp.AssistantMetas[i].Name
		assistantMetas[i].LastUseAt = rpcResp.AssistantMetas[i].LastUseAt
	}

	return &types.ListMetasResp{Metas: assistantMetas}, nil
}
